/**
 *  查看控制台
 * @author xiaoxujs
 */

import { Button, Checkbox, message, Modal } from "antd";
import { ControlBox, ModalTitleBox } from "./style";
import { FC, useCallback, useEffect, useRef, useState } from "react";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";
import { basicIp } from "../../../../../api/http";

const LookKongzhitai: FC<{
    open: boolean,
    handleKZTCallback: () => void;
    channelNo?: string; //车道编号
}> = ({
    open,
    handleKZTCallback,
    channelNo,
}) => {
        interface ItypeData {
            time: string
            printlnMessage: string
        }
        const controlBoxRef = useRef<HTMLDivElement | null>(null);
        // 定义状态来控制两个复选框的选中状态
        const [showRealTimeLoad, setShowRealTimeLoad] = useState(false);
        const [showRealTimeLevel, setShowRealTimeLevel] = useState(false);
        const [dataList, setDataList] = useState<ItypeData[]>([]);
        const ws = useRef<WebSocket | null>(null); //ws连接
        //建立ws连接
        const wsFun = useCallback(() => {
            const token = sessionStorage.getItem("token");
            let url = basicIp + `/websocket/pcConsole?satoken=${token}&channelNo=${channelNo}`;
            if (token && channelNo) {
                ws.current = new WebSocket(url);
                ws.current.onopen = (e) => {
                    console.log("ws连接成功");
                    setDataList([{ time: new Date().toLocaleString(), printlnMessage: "连接成功，等待控制台输出.." }])
                }
                ws.current.onmessage = (e) => {
                    let wsData = JSON.parse(e.data);
                    console.log(wsData);

                    setDataList(prevDataList => [...prevDataList, wsData]);
                }
                ws.current.onclose = () => {
                    message.error('控制台断开链接')
                }
            }
            return () => {
                ws.current?.close();
            };
        }, [channelNo]);

        useEffect(() => {
            wsFun();
        }, [wsFun])


        // 判断 `printlnMessage` 是否与复选框的内容匹配，并根据复选框状态决定是否显示
        const shouldShowMessage = (message: string) => {
            if (message.includes('实时装车量')) {
                return showRealTimeLoad; // 只有选中后才显示实时装车量
            }
            if (message.includes('实时料位量')) {
                return showRealTimeLevel; // 只有选中后才显示实时料位量
            }
            // 对于不包含「实时装车量」或「实时料位量」的消息，默认显示
            return true;
        };
        const hanldeThrowRed = (value: string) => {
            //正则匹配 value 
            const isError = /^\[错误\]/.test(value);
            return isError
        }


        const handleOffModal = () => {
            if (ws.current) {
                ws.current.close();
                console.log('关闭websocked')
            }
            setDataList([])
            handleKZTCallback();
        }

        return <Modal
            title={
                <ModalTitleBox>
                    <div>查看控制台</div>
                    <Checkbox onChange={(e) => setShowRealTimeLevel(e.target.checked)}>打印实时料位</Checkbox>
                    <Checkbox onChange={(e) => setShowRealTimeLoad(e.target.checked)}>打印实时装车高度</Checkbox>
                </ModalTitleBox>
            }
            open={open}
            onCancel={handleOffModal}
            getContainer={false}
            width={useWindowFontSize(800)}
            destroyOnClose
            footer={[
                <>
                    <Button key="back" onClick={() => {
                        setDataList([])
                    }}>
                        清空控制台
                    </Button>
                    <Button key="backa" onClick={handleOffModal}>
                        关闭
                    </Button>
                </>
            ]}
        >
            <ControlBox ref={controlBoxRef}>
                {dataList.map((item, index) => (
                    <div key={index}>
                        {shouldShowMessage(item.printlnMessage) && (
                            <p>
                                {item.time}
                            </p>
                        )}
                        {shouldShowMessage(item.printlnMessage) && (
                            <p style={{ color: hanldeThrowRed(item.printlnMessage) ? 'red' : '' }}>
                                {item.printlnMessage}
                            </p>
                        )}
                    </div>
                ))}
            </ControlBox>
        </Modal>
    }

export default LookKongzhitai;